#include "modbus_handler.h"
#include "../debug.h"
#include <pthread.h>
#include <unistd.h>
#include <sys/syscall.h>
#include "../misc.h"


#define SR_BUFFER_LENGTH 1000
static uint16_t sendRecvBuffer[SR_BUFFER_LENGTH];

void* modbus_tcp_master1_thread(void* arg){

    const ConfigData *config_data = get_config_data_instance();
    Misc_InitThread(__func__);
    create_client_connect(config_data->master1.request_server_ip,config_data->master1.port,config_data->master1.request_slave_id);
    return NULL;
}

void* modbus_tcp_master2_thread(void* arg){
    const ConfigData *config_data = get_config_data_instance();
    Misc_InitThread(__func__);
    create_client_connect(config_data->master2.request_server_ip,config_data->master2.port,config_data->master2.request_slave_id);
    return NULL;
}

int create_client_connect(const char *request_server_ip, int port,int request_slave_id){

    modbus_t *modbus_ctx;
    modbus_ctx = modbus_new_tcp(request_server_ip,port);
    if (modbus_ctx == NULL)
    {
        printf("[%s][%d] init tcp master fail\n", __func__, __LINE__);
        return -1;
    }

    /* 启用debug */
    modbus_set_debug(modbus_ctx, TRUE);

    /* 连接设备 */
    while(modbus_connect(modbus_ctx) < 0){
        sleep(20);
    }

    Modbus_info_t modbus_info;
    memset(&modbus_info, 0 ,sizeof(Modbus_info_t));
    modbus_info.sid = request_slave_id;
    modbus_info.fc = 0x03;
    modbus_info.addr = 0;
    modbus_info.num = 20;

    uint16_t *pBuf = sendRecvBuffer;

    while (1)
    {
        int ret = modbus_send_message_handler(modbus_ctx, &modbus_info, pBuf);
            sleep(5);
        if (ret < 0)
        {
            //printf("Error modbus_read_registers: %d\n", ret);
            if (errno == 32)
            {
                /* 重连连接设备 */
                while(modbus_connect(modbus_ctx) < 0);
            }
            continue;
        }
    }
}